package org.grow.auth.controller;

import org.grow.auth.dao.BasicInfoRepository;
import org.grow.auth.dao.UserInfoRepository;
import org.grow.auth.entity.BasicInfo;
import org.grow.auth.entity.UserInfo;
import org.grow.auth.entity.UserRegDto;
import org.grow.auth.exception.AuthException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * @Author: xwg
 * @CreateDate: 2021/10/14
 */

@RestController
@RequestMapping("/auth/userInfo")
public class UserInfoController{
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private BasicInfoRepository basicInfoRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;
//  注册相关的接口
    @PostMapping("/insert")
    public Boolean insert(@RequestBody UserRegDto userRegDto){
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(userRegDto.getUsername());
        userInfo.setPassword(userRegDto.getPassword());

        String username = userInfo.getUsername();
        UserInfo u = userInfoRepository.findByUsername(username);
        if (u != null){
            throw new AuthException("用户名已经存在");
        }
//        加密
        userInfo.setPassword(passwordEncoder.encode(userInfo.getPassword()));
        userInfo.setIsEnable(true);
        UserInfo saved = userInfoRepository.save(userInfo);
//      新增userInfo附属表 basicInfo里的一条信息
        BasicInfo basicInfo = new BasicInfo();
        basicInfo.setUsernameFk(username);
        basicInfo.setLastLoginTime(LocalDateTime.now());
        basicInfo.setNickname("unknown");
        basicInfoRepository.save(basicInfo);

        return true;
    }
//    /exist/zhangjiu001   /exist/libai
    @GetMapping("/exist/{username}")
    public Boolean exist(@PathVariable("username") String username){
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println("谁正查询该按钮 ： "+name);
        UserInfo u = userInfoRepository.findByUsername(username);
        return u != null;
    }

}
